package com.app.ui;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * 限制文本区域的字符数量的文档类
 */
public class LimitedDocument extends PlainDocument {
  private int maxSize;

  public LimitedDocument(int maxSize) {
    this.maxSize = maxSize;
  }

  @Override
  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    // 检查插入后文本长度是否超过限制
    if (getLength() + str.length() > maxSize) {
      // 如果超过限制，移除开头的一部分文本以留出空间
      int charsToRemove = str.length();
      remove(0, charsToRemove);
    }
    super.insertString(offs, str, a);
  }
}